<template>
  <div>
    <!-- 值班操作主子运单 2018/8/27 zuoW -->
    <Row>
      <i-col>
        <Form ref="tabParamForm" :model="tabParam" label-position="right" inline>
          <FormItem label="对位日期：">
            <DatePicker v-model="datePicker.timeVal" type="daterange" :options="datePicker.options" split-panels
              placeholder="对位日期" format="yyyy年MM月dd日" style="width: 230px"></DatePicker>
          </FormItem>

          <FormItem label="箱号：">
            <Input type="text" v-model="tabParam.containerNo" clearable placeholder="集装箱号"></Input>
          </FormItem>

          <FormItem label="送货地址">
            <Select v-model="tabParam.shippingAddress" placeholder="请选择送货地址" style="width: 200px" clearable>
              <Option v-for="item in addressList" :value="item.address" :key="item.address">{{ item.address }}</Option>
            </Select>
          </FormItem>

          <FormItem label="发货站：">
            <Input type="text" v-model="tabParam.startStationName" placeholder="发站" clearable></Input>
          </FormItem>

          <FormItem>
            <Button type="primary" icon="ios-search" @click="handelSearch">
              搜索
            </Button>
          </FormItem>
        </Form>
      </i-col>
    </Row>
    <Row style="margin: 10px 0;">
      <i-col>
        <Button type="primary" @click="changInfo">
          信息录入
        </Button>
      </i-col>
    </Row>
    <Row>
      <i-col span="24">
        <Tabs v-model="tabStatus">
          <template v-for="item in orderStatues">
            <TabPane :label="item.label" :name="item.val"></TabPane>
          </template>
        </Tabs>

        <!--子运单-->
        <tablePage ref="inspectionTabSubOrder" :api="dutyGetSubOrder" :param="tabParam" :isStartLoad="true" sort-name="endStationTime" sort-type="desc" :filterMethod="tableFilterMethodSubOrder" v-if="tabStatus===orderStatues[0].val">
          <template slot-scope="props">
            <Table ref="subOrdertableList" :columns="subOrderColumn" :data="nowDataList" @on-sort-change="props.sortChange" border></Table>
          </template>
        </tablePage>

        <mainOrderTable ref="mainOrderTable" :tabParam="mainOrderParam" v-if="tabStatus===orderStatues[1].val" @getCheakMainOrder="cheakMainOrder"></mainOrderTable>

      </i-col>
    </Row>

    <xlinkModal v-model="operatModal.changInfoShow" className="vertical-center-modal" title="信息录入" width="600">
      <inputInfo v-model="operatModal.changInfoShow" @submitChangeInfo="parentSubmitChangeInfo" :addressList="addressList" :orderType="tabStatus" @closeChangeInfo="operatModal.changInfoShow=false"></inputInfo>
    </xlinkModal>

    <div style="display: none">
      <!--送货地址、箱号、车队名称-->
      <div ref="tlpj">
        <div style="font-weight: bold;padding: 10px;font-size: 22px;">
         <span>{{ currentRow.shippingAddress }}
          {{ currentRow.containerNoHead+currentRow.containerNoBody }}
          {{ currentRow.fleetName }}
           {{ currentRow.truckPlate }}
         </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import tablePage from '@components/table/tablePage.vue'
  import xlinkModal from '@components/modal/xlinkModal'
  import mainOrderTable from './components/mainOrderTable'
  import inputInfo from './components/inputInfo'
  import {queryMainOrderListByPage} from '@api/backEnd/mainOrder/index'
  import {getUserAddressInfo} from '@/api/backEnd/userAddress'
  import {dutyGetSubOrder, dutyChangeMainOrder, dutyChangeSubOrder, dutyGetMainOrder, getOwnFleetDriverListWithPage} from '@api/backEnd/station'
  import moment from 'moment'
  import _ from 'lodash'
  import printUtils from '@/components/print/index'

  export default {
    name: 'orderListInspection',
    data () {
      let operatModal = {
        changInfoShow: false,
        fleetDispatchShow: false,
        sendNoticeShow: false,
        assignmentOrderShow: false,
        dispatchDriverShow: false,
        viewDetailForFleetShow: false,
        finishViewDetailShow: false
      }
      /* 子运单 */
      let subOrderColumn = [
        {
          width: 60,
          align: 'center',
          render: (h, params) => {
            return (<checkbox v-model={params.row.check}></checkbox>)
          }
        },
        {
          title: '货票号',
          key: 'waybillNo',
          width: 120
        },
        {
          title: '对位时间',
          key: 'paraPositionTime',
          width: 200,
          render: (h, params) => {
            let thisdata = params.row.mainParaPositionTime
            if (!thisdata) {
              thisdata = params.row.paraPositionTime
            }
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '发货站',
          key: 'startStationName',
          width: 100
        },
        {
          title: '送货地址',
          key: 'shippingAddress',
          width: 150
        },
        {
          title: '箱号',
          key: 'containerNoBody',
          width: 150,
          render: (h, params) => {
            let thisdata = params.row.containerNoHead + params.row.containerNoBody
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '汽车号',
          ellipsis: 'false',
          width: 180,
          render: (h, params) => {
            let truckPlate = params.row.truckPlate
            let vif = params.row.check
            if (vif) {
              let truckList = this.truckList
              return (<truckSelect
                v-model={params.row.truckPlate}
                truckList={truckList} nowTruck={params.row.truckPlate} on-truckSelectCurrent={(val) => this.truckSelectCurrentChange(val, params.row)}>
              </truckSelect>)
            } else {
              return (<span>{truckPlate}</span>)
            }
          }
        },
        {
          title: '车队名称',
          key: 'fleetName',
          width: 180
        },
        {
          title: '提煤单号',
          width: 180,
          render: (h, params) => {
            let coalNo = params.row.coalNo
            let vif = params.row.check
            if (vif) {
              return (<i-input type="text" v-model={params.row.coalNo} placeholder="请填写提煤单号"></i-input>)
            } else {
              return (<span>{coalNo}</span>)
            }
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 250,
          render: (h, params) => {
            let truckPlate = params.row.truckPlate
            let coalState = params.row.coalState
            let dyBtn = ''
            let viewDetailBtn = ''
            if (truckPlate && coalState !== 1) {
              dyBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.firstPrintCoal(params.row)}>打印</i-button>)
              viewDetailBtn = (<i-button type="primary" size="small" style="margin-right: 5px;">重新录入</i-button>)
            } else if (coalState === 1) {
              dyBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.printCoal(params.row)}>再次打印</i-button>)
              viewDetailBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.submitInfoRow(params.row)}>重新录入</i-button>)
            } else {
              viewDetailBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.submitInfoRow(params.row)}>信息录入</i-button>)
            }
            let btnArray = []
            btnArray.push(dyBtn)
            btnArray.push(viewDetailBtn)
            return (btnArray)
          }
        }
      ]
      let orderStatues = [
        {label: '子运单', val: 'subOrder'},
        {label: '主运单', val: 'mainOrder'}
      ]
      let tabStatus = orderStatues[0].val
      let checkedMainOrder = []
      let checkedSubOrder = []
      let tabParam = {
        startStationName: '',
        containerNo: '',
        containerNoHead: '',
        containerNoBody: '',
        shippingAddress: ''
        // coalState: 1
      }
      let mainOrderParam = tabParam
      let nowDataList = []
      let truckList = []
      let addressList = []
      let currentRow = []
      let datePicker = {
        timeVal: [tabParam.startTime, tabParam.endTime],
        options: {
          shortcuts: [
            {
              text: '最近一周 ',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              }
            },
            {
              text: '最近一月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              }
            },
            {
              text: '最近三月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              }
            }
          ]
        }
      }
      let datas = {
        datePicker,
        dutyGetSubOrder,
        dutyGetMainOrder,
        queryMainOrderListByPage,
        tabParam,
        orderStatues,
        subOrderColumn,
        checkedMainOrder,
        checkedSubOrder,
        operatModal,
        tabStatus,
        nowDataList,
        truckList,
        addressList,
        mainOrderParam,
        currentRow
      }
      return datas
    },
    computed: {},
    methods: {
      submitInfoRow (row) {
        row.check = true
      },
      firstPrintCoal (row) {
        console.log(this.currentRow)
        let param = [{
          coalState: 1,
          isRecord: false,
          orderNo: row.orderNo,
          paraPositionTime: row.paraPositionTime,
          shippingAddress: row.shippingAddress,
          sendAddress: row.sendAddress,
          dutyUser: row.dutyUser,
          recordUser: row.recordUser,
          fleetId: row.fleetId,
          fleetName: row.fleetName,
          driverName: row.driverName,
          driverId: row.driverId,
          truckPlate: row.truckPlate,
          grossWeight: row.grossWeight,
          tareWeight: row.tareWeight,
          netWeight: row.netWeight,
          poundNo: row.poundNo,
          coalNo: row.coalNo
        }]
        dutyChangeSubOrder(param).then(res => {
          if (res.data.isSuccess === 1) {
            this.printCoal(row)
            this.$refs['inspectionTabSubOrder'].dataRefresh()
          } else {
            this.$Notice.error({
              title: '警告',
              desc: '打印失败'
            })
          }
        })
      },
      mainOrderRefresh () {
        this.$refs['mainOrderTable'].mainOrderRefresh()
      },
      cheakMainOrder (rows) {
        console.log('mainRows', rows)
        this.checkedMainOrder = rows
        console.log(this.checkedMainOrder)
      },
      parentSubmitChangeInfo (formData) {
        let param = []
        if (this.tabStatus === this.orderStatues[0].val) {
          _.forEach(this.checkedSubOrder, (item) => {
            console.log(item)
            let itemParam = {
              orderNo: item.orderNo,
              paraPositionTime: formData.paraPositionTime ? moment(formData.paraPositionTime).format('YYYY-MM-DD HH:mm:ss') : item.paraPositionTime, // 对位时间
              shippingAddress: formData.shippingAddress ? formData.shippingAddress : item.shippingAddress, // 到达地址
              sendAddress: formData.sendAddress ? formData.sendAddress : item.sendAddress, // 发送地址
              dutyUser: formData.dutyUser ? formData.dutyUser : item.dutyUser, // 值班员
              recordUser: formData.recordUser ? formData.recordUser : item.recordUser, // 补录员
              fleetId: item.fleetId,
              fleetName: item.fleetName,
              driverName: item.driverName,
              driverId: item.driverId,
              truckPlate: item.truckPlate,
              coalNo: item.coalNo,
              grossWeight: item.grossWeight,
              tareWeight: item.tareWeight,
              netWeight: item.netWeight,
              poundNo: item.poundNo,
              isRecord: false,
              coalState: 0
            }
            param.push(itemParam)
          })
          dutyChangeSubOrder(param).then(res => {
            if (res.data.isSuccess === 1) {
              this.$Notice.success({
                title: '成功',
                desc: '信息录入成功'
              })
              this.operatModal.changInfoShow = false
              this.checkedSubOrder = []
              this.$refs['inspectionTabSubOrder'].dataRefresh()
            } else {
              this.$Notice.error({
                title: '警告',
                desc: '录入失败：' + res.data.res
              })
            }
          })
        } else if (this.tabStatus === this.orderStatues[1].val) {
          _.forEach(this.checkedMainOrder, (item) => {
            let itemParam = {
              orderNo: item.orderNo,
              paraPositionTime: formData.paraPositionTime ? moment(formData.paraPositionTime).format('YYYY-MM-DD HH:mm:ss') : item.paraPositionTime, // 对位时间
              arriveAddress: formData.arriveAddress ? formData.arriveAddress : item.arriveAddress, // 到达地址
              sendAddress: formData.sendAddress ? formData.sendAddress : item.sendAddress, // 发送地址
              dutyUser: formData.dutyUser ? formData.dutyUser : item.dutyUser, // 值班员
              recordUser: formData.recordUser ? formData.recordUser : item.recordUser
            }
            param.push(itemParam)
          })
          dutyChangeMainOrder(param).then(res => {
            if (res.data.isSuccess === 1) {
              this.$Notice.success({
                title: '成功',
                desc: '信息录入成功'
              })
              this.operatModal.changInfoShow = false
              this.checkedMainOrder = []
              this.mainOrderRefresh()
            } else {
              this.$Notice.error({
                title: '警告',
                desc: '录入失败：' + res.data.res
              })
            }
          })
        }
      },
      changInfo () {
        if (this.tabStatus === this.orderStatues[0].val) {
          let checkedSubOrder = []
          this.$refs['subOrdertableList'].rebuildData.forEach((item) => {
            if (item.check) {
              checkedSubOrder.push(item)
            }
          })
          if (checkedSubOrder.length > 0) {
            this.checkedSubOrder = checkedSubOrder
            this.operatModal.changInfoShow = true
          } else {
            this.$Notice.warning({
              title: '错误',
              desc: '请选择运单后再信息录入'
            })
            return false
          }
        } else if (this.tabStatus === this.orderStatues[1].val) {
          console.log('ccccthis.changeMainOrder', this.checkedMainOrder)
          if (this.checkedMainOrder.length > 0) {
            this.operatModal.changInfoShow = true
          } else {
            this.$Notice.warning({
              title: '错误',
              desc: '请选择运单后再信息录入'
            })
            return false
          }
        }
      },
      handelSearch () {
        this.nowDataList = []
        delete this.tabParam.startParaPositionTime
        delete this.tabParam.endParaPositionTime
        delete this.tabParam.containerNoHead
        delete this.tabParam.containerNoBody
        if (this.datePicker.timeVal[1] && this.datePicker.timeVal[0]) {
          this.tabParam.startParaPositionTime = moment(this.datePicker.timeVal[0]).format('YYYY-MM-DD') + ' 00:00:00'
          this.tabParam.endParaPositionTime = moment(this.datePicker.timeVal[1]).format('YYYY-MM-DD') + ' 23:59:59'
        } else {
        }
        let containerReg = /^[a-zA-Z]{4}[0-9]{7}$/
        if (this.tabParam.containerNo) {
          if (containerReg.test(this.tabParam.containerNo)) {
            this.tabParam.containerNoHead = this.tabParam.containerNo.substring(0, 4)
            this.tabParam.containerNoBody = this.tabParam.containerNo.substring(4, 11)
          } else {
            this.$Message.error('请输入正取的箱号')
          }
        }
        if (this.tabStatus === this.orderStatues[0].val) {
          this.$refs['inspectionTabSubOrder'].dataRefresh()
        } else if (this.tabStatus === this.orderStatues[1].val) {
          this.mainOrderParam = this.tabParam
        } else {
          this.mainOrderParam = {}
        }
      },
      getAddress () {
        let param = {
          pageIndex: 1,
          pageSize: 1000
        }
        getUserAddressInfo(param).then(res => {
          if (res.data.isSuccess === 1) {
            this.addressList = res.data.data.rows
          }
        })
      },
      truckSelectCurrentChange (val, row) {
        row.fleetId = val.fleet_id ? val.fleet_id : row.fleetId
        row.fleetName = val.fleet_name ? val.fleet_name : row.fleetName
        row.driverId = val.driver_id ? val.driver_id : row.driverId
        row.driverName = val.driver_name ? val.driver_name : row.driverName
        row.truckPlate = val.truck_no ? val.truck_no : row.truckPlate
      },
      getOwnFleetTruckList () {
        let param = {pageNumber: 1, pageSize: 0}
        getOwnFleetDriverListWithPage(param).then(res => {
          if (res.data.isSuccess === 1) {
            let resData = []
            _.forEach(res.data.data.rows, (item) => {
              if (item.truck_no) {
                resData.push(item)
              }
            })
            this.truckList = resData
          }
        })
      },
      tableFilterMethodSubOrder (data) {
        data.forEach((item) => {
          this.$set(item, 'check', false)
        })
        this.nowDataList = data
      },
      printCoal (row) {
        this.currentRow = row
        setTimeout(() => {
          printUtils.print({
            titile: '打印',
            template: this.$refs['tlpj'].innerHTML,
            width: '165mm',
            height: '92mm'
          })
        }, 200)
      }
    },
    created () {
    },
    mounted () {
      this.getOwnFleetTruckList()
      this.getAddress()
    },
    watch: {
      'tabStatus' (val, oldVal) {
        this.nowDataList = []
        this.tabParam = {
          startStationName: '',
          containerNo: '',
          containerNoHead: '',
          containerNoBody: '',
          shippingAddress: ''
        }
        if (val === this.orderStatues[0].val) {
          // this.$refs['inspectionTabSubOrder'].dataRefresh()
        } else if (val === this.orderStatues[1].val) {
          this.mainOrderParam = this.tabParam
        }
      }
    },
    components: {
      tablePage, mainOrderTable, xlinkModal, inputInfo
    }
  }
</script>

<style scoped>

</style>
